import { computed, ref, watch } from 'vue'
import { defineStore, storeToRefs } from 'pinia'
import { useAppStore } from '@/store/app'
import { useDesktopViewerStore } from '@/store/desktop-viewer'

const useSearchStore = defineStore('search-store', () => {
  const page = ref(1)

  /** 目前搜索的媒體類型 */
  const _media = ref({ value: 1 })
  const media = computed({
    get: () => _media.value.value,
    set: (v) => (_media.value.value = v),
  })

  const { isMobile } = storeToRefs(useAppStore())
  const { currIndex, mediaType: desktopMediaType, currentCreator, currentTag } = storeToRefs(useDesktopViewerStore())
  let viewerRouter = null
  let currFetcher = null
  let currCreatorId = null
  let currTag = null
  let originFetcher = null
  let originFetcherIndex = null

  function setupViewerRouter(vr) {
    viewerRouter = vr
  }

  function updateViewerRouterOriginPath() {
    const { pathname, search } = window.location
    viewerRouter.setOriginPath(pathname + search)
  }
  function toIndexedMainViewer(index) {
    viewerRouter.toIndexedMainViewer(index)
    if (isMobile.value) page.value = 2
  }

  function _toMainViewer(fetcher, index = 0) {
    viewerRouter.setFromMainViewer(fetcher)
    viewerRouter.toIndexedMainViewer(index)
    if (isMobile.value) {
      const mediaTypeRef = viewerRouter.getMediaType(0)
      mediaTypeRef.value = _media.value.value
      _media.value = mediaTypeRef
    } else {
      /**
       * TODO: 這邊同步回去的過程會錯，感覺跟桌面版的機制有關，還得深入研究看看
       */
      desktopMediaType.value.value = _media.value.value
      _media.value = desktopMediaType.value
    }

    // 重置 curr state
    currFetcher = fetcher
    currCreatorId = null
    currTag = null
  }
  function toMainViewer(fetcher) {
    if (fetcher === currFetcher || fetcher === originFetcher) {
      return
    }
    _toMainViewer(fetcher)
  }
  function toCreatorViewer(aff, username) {
    if (aff === currCreatorId) {
      return
    }

    viewerRouter.setFromCreator(aff, username)
    page.value = 2

    // 存放下來待 page 返回 1 時還原用
    originFetcher = currFetcher

    // 重置 curr state
    currFetcher = null
    currCreatorId = aff
    currTag = null
  }
  function toTagListViewer(tag, { interest, catename } = {}) {
    if (tag === currTag) {
      return
    }

    viewerRouter.setFromTagList(tag, { interest, catename })
    page.value = 2

    // 存放下來待 page 返回 1 時還原用
    originFetcher = currFetcher

    // 重置 curr state
    currFetcher = null
    currCreatorId = null
    currTag = tag
  }

  function _recoverFetcher() {
    // 還原成 originFetcher(目前在 creator 或 tag 時) 或 currFetcher(目前就在 main)
    const fetcher = originFetcher || currFetcher
    originFetcher = null
    if (fetcher !== null) {
      _toMainViewer(fetcher, originFetcherIndex)
    }
  }

  watch(page, function cb(v) {
    clearTimeout(cb.timerId)
    cb.timerId = setTimeout(() => {
      // 主頁返回第一頁時
      if (v === 1) {
        currentCreator.value = null
        currentTag.value = null
        _recoverFetcher()
      }
    }, 250) // 轉場完後(250ms)再執行
  })
  watch([currentCreator, currentTag], ([creator, tag]) => {
    if (creator || tag) page.value = 2
  })
  watch(
    currIndex,
    (v) => {
      if (page.value === 1 && currentCreator.value === null && currentTag.value === null) {
        originFetcherIndex = v
      }
    },
    { immediate: true },
  )

  const rootFetcherActive = ref(false)
  const rootScrollTabViewFetcher = computed(() => (rootFetcherActive.value ? currFetcher : null))
  function activeRootFetcher() {
    if (rootFetcherActive.value) {
      rootFetcherActive.value = false
      requestAnimationFrame(() => (rootFetcherActive.value = true))
    } else {
      rootFetcherActive.value = true
    }
  }
  function deactiveRootFetcher() {
    rootFetcherActive.value = false
  }

  return {
    page,
    media,

    setupViewerRouter,
    updateViewerRouterOriginPath,
    toIndexedMainViewer,
    toMainViewer,
    toCreatorViewer,
    toTagListViewer,

    rootScrollTabViewFetcher,
    activeRootFetcher,
    deactiveRootFetcher,
  }
})

export default useSearchStore
